#include "delement.h"
#include <QtSvg/QSvgRenderer>
#include <QtCore/QFile>
#include <QtXml/QDomDocument>
#include <QtXml/QDomElement>
#include <QtCore/QStringList>

bool loadXmlFile(const QString & xmlFile, QDomDocument & doc);

DElement::DElement(QObject *parent)
	: QObject(parent) 
{
	mCount = 0;
	mOntologies = new QStringList();
	mPatterns = new QStringList();
	mExamples = new QStringList();
}

DElement::~DElement() 
{
	if (mOntologies) delete mOntologies;
	if (mPatterns) delete mPatterns;
	if (mExamples) delete mExamples;
}

//parse the element's description file
bool DElement::parseContent(const QString &xmlFile ) 
{	
	QDomDocument doc;
	if (!loadXmlFile(xmlFile, doc))
		return false;

	QDomElement e = doc.documentElement();
	mClassName = e.attribute("class");

	QDomElement view = e.firstChildElement("view");
	if (view.isNull()) 
		qCritical("The view of element can be found!\n"
		       "\tPlease make sure the file '%s' contains 'view' element", qPrintable(xmlFile));
	mDisplayName = view.attribute("displayName");
	QString decorate = view.attribute("decorate");  
	mRenderer = setRenderer(decorate);
	mToolTip = view.attribute("toolTip");
	mStatusTip = view.attribute("statusTip");
	mWhatsThis = view.attribute("whatsThis");

	e = e.firstChildElement();
	while ( !e.isNull() ) {
		if (e.nodeName() == "function") 
			mFunction = e.text();
		else if (e.nodeName() == "ontology")
			mOntologies->append( e.text() );
		else if (e.nodeName() == "pattern") 
			mPatterns->append( e.text() );
		else if (e.nodeName() == "example")
			mExamples->append( e.text() );
		else
			parseDetail(e);

		e = e.nextSiblingElement();
	}

	return true;
}

QSvgRenderer* DElement::setRenderer(const QString &fileName)
{
	QString file = dir()+"/"+fileName;
	QSvgRenderer* renderer = new QSvgRenderer(this);
	if (!renderer->load(file))
	{
		delete renderer;
		renderer = NULL;
		qCritical("The svg file can't be load properly!\n"
			"\tPlease make sure the file '%s' is a valid svg file.", qPrintable(file));
	}

	return renderer;
}

GElement* DElement::createGraphics()
{
	++mCount; //serve for Graphics Name
	return doCreateGraphics();
}